//
//  SimplePlayerController.swift
//  简单播放界面,用来测试音乐播放相关逻辑
//
//  Created by jin on 2024/9/18.
//

import TangramKit
import UIKit

class SimplePlayerController: BaseTitleController {
    
    /**
     * LRC歌词
     * 其中的\n不要删除
     * 是每一行歌词的分隔符
     */
    static let LYRIC_LRC =  "[ti:爱的代价]\n[ar:李宗盛]\n[al:爱的代价]\n[00:00.50]爱的代价\n[00:02.50]演唱：李宗盛\n[00:06.50]\n[00:16.70]还记得年少时的梦吗\n[00:21.43]像朵永远不调零的花\n[00:25.23]陪我经过那风吹雨打\n[00:28.59]看世事无常\n[00:30.57]看沧桑变化\n[00:33.31]那些为爱所付出的代价\n[00:37.10]是永远都难忘的啊\n[00:41.10]所有真心的痴心的话\n[00:44.57]永在我心中虽然已没有他\n[00:51.46]走吧 走吧 人总要学着自己长大\n[00:59.53]走吧 走吧 人生难免经历苦痛挣扎\n[01:07.19]走吧 走吧 为自己的心找一个家\n[01:15.41]也曾伤心流泪\n[01:17.55]也曾黯然心碎\n[01:19.57]这是爱的代价\n[01:22.57]\n[01:40.67]也许我偶尔还是会想他\n[01:45.28]偶尔难免会惦记着他\n[01:49.10]就当他是个老朋友吧\n[01:52.60]也让我心疼也让我牵挂\n[01:57.37]只是我心中不再有火花\n[02:01.21]让往事都随风去吧\n[02:05.10]所有真心的痴心的话\n[02:08.53]仍在我心中\n[02:10.39]虽然已没有他\n[02:15.26]走吧 走吧 人总要学着自己长大\n[02:23.14]走吧 走吧 人生难免经历苦痛挣扎\n[02:31.26]走吧 走吧 为自己的心找一个家\n[02:39.22]也曾伤心流泪\n[02:41.54]也曾黯然心碎\n[02:43.60]这是爱的代价\n[02:46.44]\n[03:22.77]走吧 走吧 人总要学着自己长大\n[03:31.16]走吧 走吧 人生难免经历苦痛挣扎\n[03:39.08]走吧 走吧 为自己的心找一个家\n[03:47.12]也曾伤心流泪\n[03:49.41]也曾黯然心碎\n[03:51.58]这是爱的代价\n"

    static let LYRIC_KSC =  "karaoke := CreateKaraokeObject;\nkaraoke.rows := 2;\nkaraoke.TimeAfterAnimate := 2000;\nkaraoke.TimeBeforeAnimate := 4000;\nkaraoke.clear;\n\nkaraoke.add('00:27.487', '00:32.068', '一时失志不免怨叹', '347,373,1077,320,344,386,638,1096');\nkaraoke.add('00:33.221', '00:38.068', '一时落魄不免胆寒', '282,362,1118,296,317,395,718,1359');\nkaraoke.add('00:38.914', '00:42.164', '那通失去希望', '290,373,348,403,689,1147');\nkaraoke.add('00:42.485', '00:44.530', '每日醉茫茫', '298,346,366,352,683');\nkaraoke.add('00:45.273', '00:49.029', '无魂有体亲像稻草人', '317,364,380,351,326,351,356,389,922');\nkaraoke.add('00:50.281', '00:55.585', '人生可比是海上的波浪', '628,1081,376,326,406,371,375,1045,378,318');\nkaraoke.add('00:56.007', '01:00.934', '有时起有时落', '303,362,1416,658,750,1438');\nkaraoke.add('01:02.020', '01:04.581', '好运歹运', '360,1081,360,760');\nkaraoke.add('01:05.283', '01:09.453', '总嘛要照起来行', '303,338,354,373,710,706,1386');\nkaraoke.add('01:10.979', '01:13.029', '三分天注定', '304,365,353,338,690');\nkaraoke.add('01:13.790', '01:15.950', '七分靠打拼', '356,337,338,421,708');\nkaraoke.add('01:16.339', '01:20.870', '爱拼才会赢', '325,1407,709,660,1430');\nkaraoke.add('01:33.068', '01:37.580', '一时失志不免怨叹', '307,384,1021,363,357,374,677,1029');\nkaraoke.add('01:38.660', '01:43.656', '一时落魄不免胆寒', '381,411,1067,344,375,381,648,1389');\nkaraoke.add('01:44.473', '01:47.471', '那通失去希望', '315,365,340,369,684,925');\nkaraoke.add('01:48.000', '01:50.128', '每日醉茫茫', '338,361,370,370,689');\nkaraoke.add('01:50.862', '01:54.593', '无魂有体亲像稻草人', '330,359,368,376,325,334,352,389,898');\nkaraoke.add('01:55.830', '02:01.185', '人生可比是海上的波浪', '654,1056,416,318,385,416,373,1032,342,363');\nkaraoke.add('02:01.604', '02:06.716', '有时起有时落', '303,330,1432,649,704,1694');\nkaraoke.add('02:07.624', '02:10.165', '好运歹运', '329,1090,369,753');\nkaraoke.add('02:10.829', '02:15.121', '总嘛要照起来行', '313,355,362,389,705,683,1485');\nkaraoke.add('02:16.609', '02:18.621', '三分天注定', '296,363,306,389,658');\nkaraoke.add('02:19.426', '02:21.428', '七分靠打拼', '330,359,336,389,588');\nkaraoke.add('02:21.957', '02:26.457', '爱拼才会赢', '315,1364,664,767,1390');\nkaraoke.add('02:50.072', '02:55.341', '人生可比是海上的波浪', '656,1086,349,326,359,356,364,1095,338,340');\nkaraoke.add('02:55.774', '03:01.248', '有时起有时落', '312,357,1400,670,729,2006');\nkaraoke.add('03:01.787', '03:04.369', '好运歹运', '341,1084,376,781');\nkaraoke.add('03:05.041', '03:09.865', '总嘛要起工来行', '305,332,331,406,751,615,2084');\nkaraoke.add('03:10.754', '03:12.813', '三分天注定', '309,359,361,366,664');\nkaraoke.add('03:13.571', '03:15.596', '七分靠打拼', '320,362,349,352,642');\nkaraoke.add('03:16.106', '03:20.688', '爱拼才会赢', '304,1421,661,706,1490');\n"
    
    var startView: UILabel!
    var progressView: UISlider!
    var endView: UILabel!
    
    var playButtonView: QMUIButton!
    var loopModelButtonView: QMUIButton!
    
    /// 是否按下了进度条
    var isTouchProgress = false
    
    override func initViews() {
        super.initViews()
        initTableViewSafeArea()
        setBackgroundColor(.colorLightWhite)
        
        // 进度容器
        let progressContainer = ViewFactoryUtil.orientationContainer()
        progressContainer.tg_gravity = TGGravity.vert.center
        progressContainer.tg_space = PADDING_MEDDLE
        progressContainer.tg_padding = UIEdgeInsets(top: PADDING_MEDDLE, left: PADDING_OUTER, bottom: PADDING_MEDDLE, right: PADDING_OUTER)
        container.addSubview(progressContainer)
        
        startView = UILabel()
        startView.tg_width.equal(.wrap)
        startView.tg_height.equal(.wrap)
        startView.text = "00:00"
        progressContainer.addSubview(startView)
        
        progressView = UISlider()
        progressView.tg_width.equal(.fill)
        progressView.tg_height.equal(.wrap)
        
        progressView.value = 0
        progressContainer.addSubview(progressView)
        
        endView = UILabel()
        endView.tg_width.equal(.wrap)
        endView.tg_height.equal(.wrap)
        endView.text = "00:00"
        progressContainer.addSubview(endView)
        
        // 按钮容器
        let controlContainer = ViewFactoryUtil.orientationContainer()
        controlContainer.tg_gravity = TGGravity.vert.center
        controlContainer.tg_padding = UIEdgeInsets(top: PADDING_MEDDLE, left: PADDING_OUTER, bottom: PADDING_MEDDLE, right: PADDING_OUTER)
        container.addSubview(controlContainer)
        
        var buttonView = QMUIButton()
        buttonView.tg_width.equal(.fill)
        buttonView.tg_height.equal(.wrap)
        buttonView.setTitle("上一曲", for: .normal)
        buttonView.addTarget(self, action: #selector(onPreviousClick(_:)), for: .touchUpInside)
        controlContainer.addSubview(buttonView)
        
        playButtonView = QMUIButton()
        playButtonView.tg_width.equal(.fill)
        playButtonView.tg_height.equal(.wrap)
        playButtonView.setTitle("播放", for: .normal)
        playButtonView.addTarget(self, action: #selector(onPlayClick(_:)), for: .touchUpInside)
        controlContainer.addSubview(playButtonView)
        
        buttonView = QMUIButton()
        buttonView.tg_width.equal(.fill)
        buttonView.tg_height.equal(.wrap)
        buttonView.setTitle("下一曲", for: .normal)
        buttonView.addTarget(self, action: #selector(onNextClick(_:)), for: .touchUpInside)
        controlContainer.addSubview(buttonView)
        
        loopModelButtonView = QMUIButton()
        loopModelButtonView.tg_width.equal(.fill)
        loopModelButtonView.tg_height.equal(.wrap)
        loopModelButtonView.setTitle("列表循环", for: .normal)
        loopModelButtonView.addTarget(self, action: #selector(onLoopModelClick(_:)), for: .touchUpInside)
        controlContainer.addSubview(loopModelButtonView)
    }
    
    override func initDatum() {
        super.initDatum()
//        let data = Song()
//        data.title = "测试音乐"
//        MusicPlayerManager.shared()
//            .play(uri: "http://course-music-dev.ixuea.com/assets/wangbiliaodewenrou_andongyang.mp3", data: data)
        //显示循环模式
        showLoopModel()
        
        var result = LyricParser.parse(VALUE0,SimplePlayerController.LYRIC_LRC)
        print("SimplePlayerController parse lrc \(result.datum)")
        
        //KSC歌词解析
        result = LyricParser.parse(VALUE10,SimplePlayerController.LYRIC_KSC)
        print("SimplePlayerController parse ksc \(result.datum)")
    }
    
    override func initListeners() {
        super.initListeners()
        // 监听应用进入前台了
        NotificationCenter.default.addObserver(self, selector: #selector(onEnterForeground), name: UIApplication.didBecomeActiveNotification, object: nil)
        
        // 监听应用进入后台了
        NotificationCenter.default.addObserver(self, selector: #selector(onEnterBackground), name: UIApplication.willResignActiveNotification, object: nil)
        
        // 进度条拖拽监听
        progressView.addTarget(self, action: #selector(progressChanged(_:)), for: .valueChanged)
        progressView.addTarget(self, action: #selector(progressTouchDown(_:)), for: .touchDown)
        progressView.addTarget(self, action: #selector(progressTouchUp(_:)), for: .touchUpInside)
        progressView.addTarget(self, action: #selector(progressTouchUp(_:)), for: .touchUpOutside)
    }
    
    /// 进度条拖拽回调
    @objc func progressChanged(_ sender: UISlider) {
        // 将拖拽进度显示到界面
        // 用户就很方便的知道自己拖拽到什么位置
        startView.text = SuperDateUtil.second2MinuteSecond(sender.value)
        
        // 音乐切换到拖拽位置播放
        MusicListManager.shared().seekTo(sender.value)
    }
    
    /// 进度条按下
    @objc func progressTouchDown(_ sender: UISlider) {
        isTouchProgress = true
    }
    
    /// 进度条抬起
    @objc func progressTouchUp(_ sender: UISlider) {
        isTouchProgress = false
    }
    
    func setMusicPlayerDelegate() {
        MusicPlayerManager.shared().delegate = self
        print("SimplePlayerController setMusicPlayerDelegate")
    }
    
    func removeMusicPlayerDelegate() {
        MusicPlayerManager.shared().delegate = nil
        print("SimplePlayerController removeMusicPlayerDelegate")
    }
    
    /// 进入前台了
    @objc func onEnterForeground() {
        initPlayData()
        setMusicPlayerDelegate()
    }
    
    /// 进入后台了
    @objc func onEnterBackground() {
        removeMusicPlayerDelegate()
    }
    
    /// 视图即将可见方法
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    /// 视图已经可见
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        print("SimplePlayerController viewDidAppear")
        setMusicPlayerDelegate()
        
        initPlayData()
    }
    
    /// 视图即将消失
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    /// 视图已经消失
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        removeMusicPlayerDelegate()
    }
    
    @objc func onPreviousClick(_ sender: QMUIButton) {
        MusicListManager.shared().play(MusicListManager.shared().previous())
    }
    
    @objc func onPlayClick(_ sender: QMUIButton) {
        playOrPause()
    }
    
    @objc func onNextClick(_ sender: QMUIButton) {
        MusicListManager.shared().play(MusicListManager.shared().next())
    }
    
    @objc func onLoopModelClick(_ sender: QMUIButton) {
        //更改循环模式
        MusicListManager.shared().changeLoopModel()
        
        //显示循环模式
        showLoopModel()
    }
    
    func showLoopModel() {
        //获取当前循环模式
        let model = MusicListManager.shared().model
        
        switch model {
        case .list:
            loopModelButtonView.setTitle("列表循环", for: .normal)
        case .random:
            loopModelButtonView.setTitle("随机循环", for: .normal)
        default:
            loopModelButtonView.setTitle("单曲循环", for: .normal)
        }
    }
    
    /// 显示播放数据
    func initPlayData() {
        // 显示初始化数据
        showInitData()
        
        // 显示音乐时长
        showDuration()
        
        // 显示播放进度
        showProgress()
        
        // 显示播放状态
        showMusicPlayStatus()
        
        //选中当前播放的音乐
        scrollPosition()
    }
    
    /// 显示初始化数据
    func showInitData() {
        // 获取当前播放的音乐
        let data = MusicListManager.shared().data!

        // 显示标题
        title = data.title
    }
    
    /// 显示音乐时长
    func showDuration() {
        let duration = MusicListManager.shared().data!.duration
        
        if duration > 0 {
            endView.text = SuperDateUtil.second2MinuteSecond(duration)
            progressView.maximumValue = duration
        }
    }
    
    /// 显示播放进度
    func showProgress() {
        if isTouchProgress {
            return
        }
        
        let progress = MusicListManager.shared().data!.progress
        
        if progress > 0 {
            startView.text = SuperDateUtil.second2MinuteSecond(progress)
            progressView.value = progress
        }
    }
    
    func showMusicPlayStatus() {
        if MusicPlayerManager.shared().isPlaying() {
            showPauseStatus()
        } else {
            showPlayStatus()
        }
    }
    
    /// 播放或暂停
    func playOrPause() {
        if MusicPlayerManager.shared().isPlaying() {
            MusicPlayerManager.shared().pause()
        } else {
            MusicPlayerManager.shared().resume()
        }
    }
    
    /// 显示播放状态
    func showPlayStatus() {
        playButtonView.setTitle("播放", for: .normal)
    }
    
    /// 显示暂停状态
    func showPauseStatus() {
        playButtonView.setTitle("暂停", for: .normal)
    }
    
    /// 选中当前播放的音乐
    func scrollPosition()  {
        //获取当前音乐在播放列表中的索引
        let data = MusicListManager.shared().data!
        
        let datumOC = MusicListManager.shared().datum as NSArray
        let index = datumOC.index(of: data)
        
        if index != -1 {
            //创建indexPath
            let indexPath = IndexPath(row: index, section: 0)
            
            //延迟后选中当前音乐
            //因为前面执行可能是删除Cell操作
            DispatchQueue.main.asyncAfter(deadline: .now()+0.5){
                self.tableView.selectRow(at: indexPath, animated: true, scrollPosition: .middle)
            }
        }
    }
}

// MARK: -  播放管理器代理
extension SimplePlayerController: MusicPlayerManagerDelegate {
    func onPrepared(data: Song) {
        // 显示初始化数据
        showInitData()

        // 显示时长
        showDuration()
        
        //选中当前音乐
        scrollPosition()
    }
    
    func onPaused(data: Song) {
        showPlayStatus()
    }
    
    func onPlaying(data: Song) {
        showPauseStatus()
    }
    
    func onProgress(data: Song) {
        showProgress()
    }
    
    func onLyricReady(data: Song) {}
    
    func onError(data: Song) {}
}

// MARK: -  列表数据源和代理
extension SimplePlayerController{
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return MusicListManager.shared().datum.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let data = MusicListManager.shared().datum[indexPath.row]
        
        var cell = tableView.dequeueReusableCell(withIdentifier: Constant.CELL)
        
        if cell == nil{
            //也可以在这里创建，也可以在前面注册
            cell = UITableViewCell(style: .value1, reuseIdentifier: Constant.CELL)
        }
        
        cell!.textLabel?.text = data.title
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let data = MusicListManager.shared().datum[indexPath.row]
        
        MusicListManager.shared().play(data)
    }
}
